package com.keter.framework.cloud.component.interceptor;

import com.google.common.base.Strings;
import com.keter.framework.web.component.sequence.SIDHolder;
import com.keter.framework.web.util.QueryParameterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Deque;

/**
 * 为基于RestTemplate的请求自动添加SID消息头
 */
@Component
public class SIDInterceptor implements ClientHttpRequestInterceptor {

  private static final Logger logger = LoggerFactory.getLogger(SIDInterceptor.class);

  @Autowired
  protected SIDHolder sidHolder;

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
      throws IOException {
    SIDHolder.addSidToHeaders(request.getHeaders(),getSid(request));
    // 保证请求继续被执行
    return execution.execute(request, body);
  }

  private Long getSid(HttpRequest request){
    // 从url中解析读取sid：从Undertow抄了点儿代码 o(╯□╰)o
    Deque<String> sidObj = QueryParameterUtils.parseQueryString(request.getURI().toString(),"utf-8").get(SIDHolder.KEY_SID);
    if(sidObj!=null && !Strings.isNullOrEmpty(sidObj.getFirst())){
      sidHolder.setSid(Long.parseLong(sidObj.getFirst()));
      return sidHolder.get();
    }
    // 如果url中不存在则从ThreadLocal中生成或读取
    return sidHolder.getOrGenerate();
  }
}